//
// GPSMapEdit
// (c) Konstantin Galichsky (kg@geopainting.com), 2006-2007
//
// Waypoints, tracks, routes info.
//

# include "StdAfx.h"
# include "WTR.h"
# include "Map.h"
# include "Globals.h"

float rgn_element_extra_t::GetSpeed (size_t _cPoint, const points_t & _points) const {
	const size_t cPointsExtra = TrackPoints.size ();
	if (_cPoint >= cPointsExtra)
		return -1;

	const trackpoint_info_t & tpi0 = TrackPoints [_cPoint];
	if (tpi0.wFlags & trackpoint_info_t::defSpeed)
		return tpi0.fSpeed;

	const size_t cPoints = _points.size ();
	if (_cPoint + 1 < cPointsExtra && _cPoint + 1 < cPoints) {
		// Leg length.
		const point_t & point0 = _points [_cPoint];
		const float fCosY = ::cos (c_PI*point0.y/180);
		const point_t & point1 = _points [_cPoint + 1];
		const double dLegLength = ::hypot (point1.y - point0.y, (point1.x - point0.x)*fCosY)*40e6/360;

		const trackpoint_info_t & tpi1 = TrackPoints [_cPoint + 1];

		// Leg time.
		if (
			(tpi0.wFlags & trackpoint_info_t::defTime) &&
			(tpi1.wFlags & trackpoint_info_t::defTime)
		) {
			const double dLegTime = (tpi1.dtTime - tpi0.dtTime)*24*60*60;

			if (dLegTime > 0)
				return 3.6*dLegLength/::fabs (dLegTime);
		}
	}

	return -1;
}
